import * as ModelProto from '@/proto/model/ModelProto'
import ListenerInterface from '@/listener/ListenerInterface'
import ConnectListener from '@/listener/ConnectListener'
import AuthListener from '@/listener/AuthListener'
import {Command} from '@/const/Constants'
//定义消息分发总线
class MessageBus {
  //定义监听器容器
  private listeners: Map<number, ListenerInterface> = new Map()

  constructor() {
    this.listeners.set(Command.CONNECT, new ConnectListener())
    this.listeners.set(Command.AUTH, new AuthListener())
  }

  // 添加事件监听器
  addEventListener(command: number, listener: ListenerInterface): void {
    this.listeners.set(command, listener)
  }

  //消息分发处理
  dispatch(response: ModelProto.Response) {
    let listener
    if (response && response.header && response.header.command) {
      listener = this.listeners.get(response.header.command)
    }
    if (listener) {
      listener.apply(response)
    }
  }
}

const messageBus = new MessageBus()

export default messageBus
